package com.canyou.redmine.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.allen.library.SuperTextView;
import com.canyou.redmine.R;
import com.canyou.redmine.model.Bean;
import com.canyou.redmine.model.Member;
import com.canyou.redmine.model.MemberPage;
import com.canyou.redmine.model.NewIssue;
import com.canyou.redmine.model.Project;
import com.canyou.redmine.network.CanYouAPI;
import com.canyou.redmine.ui.base.BaseActivity;
import com.canyou.redmine.util.CanYouLog;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sdsmdg.tastytoast.TastyToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 新建任务
 *
 * @author ryk
 */
public class NewIssueActivity extends BaseActivity implements SuperTextView.OnClickListener {

    /**
     * 任务主题
     */
    private SuperTextView tvSubject;
    /**
     * 任务耗时
     */
    private SuperTextView tvEstimated;
    /**
     * 父任务
     */
    private SuperTextView tvParent;
    /**
     * 所属项目
     */
    private SuperTextView tvProject;
    /**
     * 任务状态
     */
    private SuperTextView tvStatus;
    /**
     * 指派
     */
    private SuperTextView tvAssigned;
    /**
     * 完成度
     */
    private SuperTextView tvDoneRatio;
    /**
     * 跟踪
     */
    private SuperTextView tvTracker;
    /**
     * 优先级
     */
    private SuperTextView tvPriority;
    /**
     * 开始时间
     */
    private SuperTextView tvStartDate;
    /**
     * 结束时间
     */
    private SuperTextView tvDueDate;

    private NewIssue issue;
    private int projectId;
    private String projectName;

    private List<Bean> trackerList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_issue_new);
        Bundle bundle = getIntent().getExtras();

        projectId = bundle.getInt("projectId", 0);
        projectName = bundle.getString("projectName", "");
        issue = new NewIssue();
        issue.setProject_id(projectId);
        initUI();
    }

    private void initUI() {
        setBackButton(true);
        setTitle("创建任务");
        tvProject = findViewById(R.id.tv_project_name);
        tvProject.setRightString(projectName);

        tvSubject = findViewById(R.id.tv_issue_subject);
        tvParent = findViewById(R.id.tv_issue_parent);
        tvStatus = findViewById(R.id.tv_issue_status);
        tvAssigned = findViewById(R.id.tv_issue_assigned);
        tvDoneRatio = findViewById(R.id.tv_issue_done_ratio);
        tvTracker = findViewById(R.id.tv_issue_tracker);
        tvPriority = findViewById(R.id.tv_issue_priority);
        tvStartDate = findViewById(R.id.tv_issue_start_date);
        tvDueDate = findViewById(R.id.tv_issue_due_date);

        tvStatus.setOnClickListener(this);
        tvAssigned.setOnClickListener(this);
        tvSubject.setOnClickListener(this);
        tvTracker.setOnClickListener(this);
        tvPriority.setOnClickListener(this);

        tvPriority.setRightString("中");
        issue.setPriority_id(2);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.tv_issue_status:
                getIssueStuats();
                break;
            case R.id.tv_issue_assigned:
                getMembers(projectId);
                break;
            case R.id.tv_issue_subject:
                new MaterialDialog.Builder(this)
                        .title("请填写任务")
                        .content("任务主题：")
                        .inputType(InputType.TYPE_CLASS_TEXT)
                        .positiveText("确定")
                        .input("", "", false, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                issue.setSubject(input.toString());
                                tvSubject.setRightString(input);
                            }
                        })
                        .show();
                break;
            case R.id.tv_issue_tracker:
                getProject(projectId);
                break;
            case R.id.tv_issue_priority:
                break;

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_submit:
                submit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    /**
     * 提交数据
     */
    private void submit() {
        if (TextUtils.isEmpty(issue.getSubject())) {
            AlertToast("任务主题不能为空", TastyToast.INFO);
            return;
        }
        if (issue.getTracker_id() == 0) {
            AlertToast("请选择任务跟踪", TastyToast.INFO);
            return;
        }
        if (issue.getStatus_id() == 0) {
            AlertToast("请选择任务状态", TastyToast.INFO);
            return;
        }
        if (issue.getAssigned_to_id() == 0) {
            AlertToast("请选择指派人员", TastyToast.INFO);
            return;
        }
        if (issue.getPriority_id() == 0) {
            AlertToast("请选择任务优先级", TastyToast.INFO);
            return;
        }

        CanYouAPI.createIssue(getApplicationContext(), "{\"issue\":" + JSON.toJSONString(issue) + "}", new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                CanYouLog.e(responseString);
                AlertToast(responseString, TastyToast.ERROR);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                CanYouLog.i(responseString);
                finish();
            }

            @Override
            public void onStart() {
                super.onStart();
                showHUD("正在提交...");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeHUD();
            }
        });
    }

    /**
     * 获取项目信息（跟踪集）
     *
     * @param projectId
     */
    private void getProject(int projectId) {
        CanYouAPI.getProject(projectId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                CanYouLog.e(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                String projectJSON = "";
                try {
                    JSONObject object = new JSONObject(responseString);
                    projectJSON = object.getString("project");
                } catch (JSONException e) {
                    CanYouLog.e("json error:" + e.getLocalizedMessage());
                }
                Project project = JSON.parseObject(projectJSON, Project.class);
                trackerList = project.getTrackers();

                List<String> array = new ArrayList<>();
                for (Bean item : trackerList) {
                    array.add(item.getName());
                }
                new MaterialDialog.Builder(NewIssueActivity.this)
                        .title("请选择跟踪：")
                        .items(array)
                        .itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                issue.setTracker_id(trackerList.get(which).getId());
                                tvTracker.setRightString(text);
                                return false;
                            }
                        })
                        .show();
            }

            @Override
            public void onStart() {
                super.onStart();
                showHUD();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeHUD();
            }
        });
    }


    /**
     * 获取任务状态集
     */
    private void getIssueStuats() {
        CanYouAPI.getIssueSatuses(new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                CanYouLog.i(responseString);
                String json = "";
                try {
                    JSONObject object = new JSONObject(responseString);
                    json = object.getString("issue_statuses");
                } catch (JSONException e) {
                    CanYouLog.e("json error:" + e.getLocalizedMessage());
                }
                final List<Bean> issue_statuses = JSON.parseArray(json, Bean.class);
                List<String> array = new ArrayList<>();
                for (Bean bean : issue_statuses) {
                    array.add(bean.getName());
                }

                new MaterialDialog.Builder(NewIssueActivity.this)
                        .title("请选择任务状态")
                        .items(array)
                        .itemsCallbackSingleChoice(
                                0,
                                new MaterialDialog.ListCallbackSingleChoice() {
                                    @Override
                                    public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                        issue.setStatus_id(issue_statuses.get(which).getId());
                                        tvStatus.setRightString(text);
                                        return false;
                                    }
                                })
                        .show();
            }

            @Override
            public void onStart() {
                super.onStart();
                showHUD();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeHUD();
            }
        });
    }

    /**
     * 获取项目成员
     *
     * @param projectId 项目id
     */
    private void getMembers(int projectId) {
        CanYouAPI.getMembersByProjectId(projectId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                CanYouLog.e(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                MemberPage page = JSON.parseObject(responseString, MemberPage.class);
                final List<Member> members = page.getMemberships();
                List<String> array = new ArrayList<>();
                for (Member member : members) {
                    array.add(member.getUser().getName());
                }

                new MaterialDialog.Builder(NewIssueActivity.this)
                        .title("指派给：")
                        .items(array)
                        .itemsCallbackSingleChoice(
                                0,
                                new MaterialDialog.ListCallbackSingleChoice() {
                                    @Override
                                    public boolean onSelection(MaterialDialog dialog, View itemView,
                                                               int which, CharSequence text) {
                                        issue.setAssigned_to_id(members.get(which).getUser().getId());
                                        tvAssigned.setRightString(text);
                                        return false;
                                    }
                                })
                        .show();
                CanYouLog.i(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                showHUD();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeHUD();
            }
        });
    }
}
